#! /usr/local/bin/python3
# versionV1.4
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from PIL import ImageGrab
from PIL import Image
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from openpyxl import load_workbook
from glob import glob
from email.mime.base import MIMEBase
from email import encoders
import datetime
import zipfile
import smtplib
import random
import ddddocr
import time
import os as os
import shutil as shutil
import hmac
import hashlib
import base64
import urllib.parse
import requests
import json
import sys
today = datetime.date.today() # 1. 获取「今天」
last_month = today.replace(month=today.month - 1) # 2.获取前一个月
lastmoth = last_month.strftime('%Y-%m')



def unzip_file(zip_src, dst_dir):
    r = zipfile.is_zipfile(zip_src)
    if r:
        fz = zipfile.ZipFile(zip_src, 'r')
        for file in fz.namelist():
            fz.extract(file, dst_dir)
    else:
        print('This is not zip')

# #定义一个清楚输入函数
def clean_and_input(element, text: str):
    element.send_keys(Keys.CONTROL, "a")
    element.send_keys(text)

def mymovefile(srcfile,dstpath):                       # 移动函数
    if not os.path.isfile(srcfile):
        print ("%s not exist!"%(srcfile))
    else:
        fpath,fname=os.path.split(srcfile)             # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)                       # 创建路径
        shutil.move(srcfile, dstpath + fname)          # 移动文件
        print("move %s -> %s" % (srcfile, dstpath + fname))


# 获取时间戳，签名值
def getSignTimestamp(signature):
    timestamp = str(round(time.time() * 1000))
    secret = signature
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return (timestamp, sign)


# 发送text信息到钉钉
def sendDing(url, text):
    headers = {
        'Content-Type': 'application/json',
    }
    data = {
        'text': {
            'content': text,
        },
        'msgtype': 'text'
    }
    r = requests.post(url, headers=headers, data=json.dumps(data)).text
    json_r = json.loads(r)
    if json_r['errcode'] == 0:
        print("发送成功")
    else:
        print("发送失败")
        print(json_r['errcode'])
        print(json_r['errmsg'])

# 报错信息
def DingText(text):
    signature = 'secxxxxx'
    (times, signs) = getSignTimestamp(signature)
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=48ff4f559cef9019f60145d65f308da1ae691f808f8f29fc7c55b164f8dd94d4'
    urls = webhook + '&timestamp=' + times + '&sign=' + signs
    sendDing(urls, text)

def TxZhandan() -> int:
    chrome_options = Options()
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--headless')
    chrome_options.add_argument("lang=zh_CN.UTF-8")
    chrome_options.add_argument('window-size=1920x1080')
    prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': '/usr/local/src/zhandan'}
    chrome_options.add_experimental_option('prefs', prefs)
    i = 1
    for lines in open('account_tx.txt', 'r'):
        if 'mainAc:' in lines:
            'https://cloud.tencent.com/login/subAccount?s_url=https%3A%2F%2Fconsole.cloud.tencent.com%2Fexpense%2Fbill%2FdownloadCenter'
            mainAc = lines.split(':')[1]
            account = lines.split(':')[2]
            passwd = lines.split(':')[3]
            url = (
                'https://cloud.tencent.com/login/subAccount?s_url=https%3A%2F%2Fconsole.cloud.tencent.com%2Fexpense%2Fbill%2FdownloadCenter')
            driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='/usr/bin/chromedriver')
            time.sleep(2)
            driver.get(url)
            time.sleep(random.randint(8, 10))
            clean_and_input(driver.find_element(by=By.NAME, value='account'), mainAc)
            time.sleep(random.randint(2, 3))
            clean_and_input(driver.find_element(by=By.NAME, value="username"), account)
            time.sleep(random.randint(1, 3))
            try:
                driver.find_element(by=By.NAME, value="password").send_keys(passwd)
            except:
                driver.get_screenshot_as_file('error_passwd.png')
            time.sleep(random.randint(10, 12))
            #if i == 1:
            driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[2]/div/div[2]/div[2]/div[2]/a').click()
            #else:
                #driver.find_element(by=By.XPATH,value='/html/body/div[2]/div/div[1]/div[1]/div/div/div[2]/form[1]/div/div[1]/a').click()
                # / html / body / div[2] / div / div[1] / div[1] / div / div / div[2] / form[1] / div / div[1] / a
                #time.sleep(random.randint(5, 8))
                #driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[2]/div/div[2]/div[2]/div[2]/a').click()
            time.sleep(random.randint(8, 10))
            try:
                driver.find_element(by=By.XPATH,value='/html/body/div[5]/div[2]/div/div/div[2]/div/button[1]').click()
            except:
                print('无弹窗')
            driver.get_screenshot_as_file('tx.png')
            driver.find_element(by=By.XPATH,value='/html/body/div[1]/div[2]/div[2]/div/main/div/div[2]/div/div/div[1]/div/div/div[1]/div[2]/div/button').click()
            time.sleep(random.randint(10, 12))
            driver.find_element(by=By.XPATH,
                                value='//*[@id="tea-overlay-root"]/div/div[3]/div/div[2]/div[3]/div[2]/button').click()
            time.sleep(30)
            if i == 1:
                for filename in os.listdir('/usr/local/src/zhandan/'):
                    unzip_file('/usr/local/src/zhandan/%s' % (filename), '/usr/local/src/zhandan_auto/%s/冰雪/腾讯云'% (lastmoth))
                    time.sleep(2)
                    os.remove('/usr/local/src/zhandan/%s' % (filename))
            elif i == 2:
                for filename in os.listdir('/usr/local/src/zhandan/'):
                    unzip_file('/usr/local/src/zhandan/%s' % (filename), '/usr/local/src/zhandan_auto/%s/流连/腾讯云' % (lastmoth))
                    time.sleep(2)
                    os.remove('/usr/local/src/zhandan/%s' % (filename))
            else:
                for filename in os.listdir('/usr/local/src/zhandan/'):
                    unzip_file('/usr/local/src/zhandan/%s' % (filename), '/usr/local/src/zhandan_auto/%s/掌玩/腾讯云' % (lastmoth))
                    time.sleep(2)
                    os.remove('/usr/local/src/zhandan/%s' % (filename))
            DingText('腾讯账户%s下载完毕' % (i))
            i = i + 1
            driver.close()
            time.sleep(2)
    return 1



if __name__ == '__main__':
    TxZhandan()